const axios = require('axios');
const fs = require('fs');
const path = require('path');

const makeHttpRequest = async (url, params = {}, headers = {}) => {
    try {
        const response = await axios.get(url, { params, headers });
        return response.data;
    } catch (error) {
        console.error(`Error fetching data from ${url}:`, error);
        throw error;
    }
};

const createDirectory = (dirPath) => {
    if (!fs.existsSync(dirPath)) {
        fs.mkdirSync(dirPath, { recursive: true });
    }
};

const downloadFile = async (url, filePath, headers = {}) => {
    const writer = fs.createWriteStream(filePath);
    const response = await axios.get(url, { responseType: 'stream', headers });

    response.data.pipe(writer);

    return new Promise((resolve, reject) => {
        writer.on('finish', resolve);
        writer.on('error', reject);
    });
};

module.exports = {
    makeHttpRequest,
    createDirectory,
    downloadFile,
};